<template>
    <div class="role-page">
        <!-- 标题 -->
        <div class="page-header">
            <h2>角色管理</h2>
        </div>

        <!-- 查询表单 -->
        <el-card class="search-card">
            <el-form :model="query" inline @keyup.enter.native="handleSearch">
                <el-form-item label="角色名称">
                    <el-input v-model="query.roleName" placeholder="按角色名称模糊查询" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :loading="loading" @click="handleSearch"><el-icon><Search /></el-icon>查询</el-button>
                     <el-button type="primary" @click="openCreateDialog">新增角色</el-button>
                    <el-button @click="handleReset"><el-icon><Refresh /></el-icon>重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 表格 -->
        <el-card class="table-card">
            <div class="table-header">
                <h3>角色列表</h3>
            </div>

            <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="RoleName" label="角色名称" min-width="160" />
                <el-table-column prop="Status" label="状态" width="120">
                    <template #default="{ row }">
                        <el-tag :type="row.Status ? 'success' : 'info'">{{ row.Status ? '启用' : '停用' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="CreateTime" label="创建时间" width="200">
                    <template #default="{ row }">{{ formatDate(row.CreateTime) }}</template>
                </el-table-column>
                <el-table-column label="权限" min-width="240" show-overflow-tooltip>
                    <template #default="{ row }">{{(row.Permissions || []).map(p => p.PermissionName).join('，')
                        }}</template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination v-model:current-page="pageIndex" v-model:page-size="pageSize" :total="total"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 新增角色弹窗 -->
        <el-dialog v-model="dialogVisible" title="新增角色" width="600px" :close-on-click-modal="false">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="96px">
                <el-form-item label="角色名称" prop="RoleName">
                    <el-input v-model="form.RoleName" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="form.Status" active-text="启用" inactive-text="停用" />
                </el-form-item>
                <el-form-item label="权限">
                    <div class="perm-picker">
                        <el-scrollbar max-height="220" class="perm-list" v-loading="permLoading">
                            <el-checkbox-group v-model="form.PermissionIds">
                                <el-checkbox v-for="p in permissions" :key="p.PermissionsId" :label="p.PermissionsId">
                                    {{ p.PermissionName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-scrollbar>
                    </div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getRoles, createRole, getPermissions, type RoleItem, type PermissionItem } from '@/api/role'

// 查询参数与分页
const query = reactive({
    roleName: ''
})
const pageIndex = ref(1)
const pageSize = ref(10)

// 数据
const loading = ref(false)
const tableData = ref<RoleItem[]>([])
const total = ref(0)

const formatDate = (d: string) => {
    return d ? new Date(d).toLocaleString('zh-CN') : ''
}

const fetchData = async () => {
    loading.value = true
    try {
        const res = await getRoles({
            roleName: query.roleName?.trim() || undefined,
            pageIndex: pageIndex.value,
            pageSize: pageSize.value
        })
        if (res.code === 200) {
            tableData.value = res.PageData || []
            total.value = res.TotalCount || 0
        } else {
            ElMessage.error(res.msg || '获取角色数据失败')
        }
    } catch (e) {
        console.error(e)
        ElMessage.error('获取角色数据失败')
    } finally {
        loading.value = false
    }
}

const handleSearch = () => {
    pageIndex.value = 1
    fetchData()
}

const handleReset = () => {
    query.roleName = ''
    pageIndex.value = 1
    pageSize.value = 10
    fetchData()
}

const handleSizeChange = (size: number) => {
    pageSize.value = size
    pageIndex.value = 1
    fetchData()
}

const handleCurrentChange = (page: number) => {
    pageIndex.value = page
    fetchData()
}

// ========== 新增角色逻辑 ==========
const dialogVisible = ref(false)
const submitLoading = ref(false)
const permLoading = ref(false)
const permissions = ref<PermissionItem[]>([])
// 权限筛选关键字与过滤后的列表
const permKeyword = ref('')
const filteredPermissions = computed(() => {
    const kw = permKeyword.value.trim().toLowerCase()
    if (!kw) return permissions.value
    return permissions.value.filter(p => (p.PermissionName || '').toLowerCase().includes(kw))
})
const formRef = ref<FormInstance>()
const form = reactive({
    RoleName: '',
    Status: true,
    PermissionIds: [] as number[]
})
const rules: FormRules = {
    RoleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
}

const openCreateDialog = async () => {
    // 重置表单
    form.RoleName = ''
    form.Status = true
    form.PermissionIds = []
    dialogVisible.value = true

    // 拉取权限
    permLoading.value = true
    try {
        const res = await getPermissions()
        if (res.code === 200) {
            permissions.value = res.PageData || []
        } else {
            ElMessage.error(res.msg || '获取权限失败')
        }
    } catch (e) {
        console.error(e)
        ElMessage.error('获取权限失败')
    } finally {
        permLoading.value = false
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
        if (!valid) return
        submitLoading.value = true
        try {
            const res = await createRole({
                RoleName: form.RoleName,
                Status: form.Status,
                PermissionIds: form.PermissionIds
            })
            if (res.code === 200) {
                ElMessage.success(res.msg || '添加成功')
                dialogVisible.value = false
                fetchData()
            } else {
                ElMessage.error(res.msg || '添加失败')
            }
        } catch (e) {
            console.error(e)
            ElMessage.error('添加失败')
        } finally {
            submitLoading.value = false
        }
    })
}

onMounted(fetchData)
</script>

<style scoped>
.role-page {
    padding: 12px;
}

.page-header {
    margin-bottom: 12px;
}

.page-header h2 {
    margin: 0 0 4px;
}

.search-card {
    margin-bottom: 12px;
}

.table-card {
    margin-top: 0;
}

.table-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}

.table-header .total {
    color: #909399;
    font-size: 13px;
}

.pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 12px;
}

/* 新增：权限多选面板样式 */
.perm-picker {
    width: 100%;
    border: 1px solid var(--el-border-color);
    border-radius: 6px;
    padding: 8px;
}
.perm-toolbar { margin-bottom: 8px; }
.perm-list { padding: 4px 8px; }
</style>